# -*- coding: utf-8 -*-

import datetime,time,functools

from django.db import models
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.contrib import admin
from django.template import RequestContext, Context, loader,Template

import mptt
from djangoext.admin import ListConfig,TreeConfig


""" Models """

class Project(models.Model):
    cdate = models.DateTimeField('Date',auto_now_add=True)
    name = models.CharField('Projectname',max_length=50)
    responsible = models.ForeignKey(User, null=True, blank=True, related_name='projects',verbose_name='Responsible')
    parent = models.ForeignKey('self', null=True, blank=True, related_name='children',verbose_name='Parent project')
    index = models.IntegerField('Indeks',default=0)
    time_estimate = models.IntegerField('Time estimate',max_length=50)

    class Meta:
        get_latest_by='cdate'
        ordering = ('name',)

    def __unicode__(self):
        return self.name

    def get_treename(self):
        return "%s [%d]" % (self.name,self.children.all().count())

    def get_total_time_estimate(self):
        return self.time_estimate+sum([x.get_total_time_estimate() for x in self.children.all()])

    def get_total_timereg(self):
        return sum([x.minutes for x in self.timeregs.all()])

mptt.register(Project, order_insertion_by=['index'])


class Timereg(models.Model):
    cdate = models.DateTimeField('Dato oprettet',auto_now_add=True)
    note = models.CharField('Note',max_length=50)
    minutes = models.IntegerField('Minutes')
    project = models.ForeignKey(Project, null=True, blank=True, related_name='timeregs',verbose_name='Project')
    user = models.ForeignKey(User, null=True, blank=True, related_name='timereg',verbose_name='User')

    class Meta:
        get_latest_by='cdate'
        ordering = ('cdate','project',)

    def __unicode__(self):
        return self.name


""" Ext config """

class ProjectConfig(ListConfig):
    cls=Project
    caption = u'Projects'
    description = u'Test project.'
    fields_list=['name','cdate','responsible','parent']
    fields_edit=['name','responsible','parent','time_estimate']
    fields_list_methods=[('get_total_time_estimate','TTE'),('get_total_timereg','TTR')]
    object_actions = [('url','View timregs','/timeregs/list/?filter.project=$pk$',False),]

class ProjectTreeConfig(TreeConfig):
    cls=Project
    caption = u'Projects'
    description = u'Test project.'
    field='get_treename'
    object_actions = [('url','View timregs','/timeregs/list/?filter.project=$pk$',False),]

class TimeregConfig(ListConfig):
    cls=Timereg
    caption = u'Timeregs'
    description = u'Test timereg.'
    fields_list=['cdate','project','user','minutes']
    fields_edit=['note','minutes','project','user']
    object_actions = [('url','View project','/projects/list/'),]
